<?php
/**
 *类名：iapPayTrade.php
 *功能  CP服务器端处理plutus平台交易返回
 *版本：1.0
 *日期：2014-06-26
'说明：
 */

date_default_timezone_set('Asia/Shanghai');
//ini_set('error_reporting', 'E_ALL ^ E_NOTICE');
set_time_limit(0);

include_once("./plutuspay/base.php");
include_once("./plutuspay/config.php");

include_once("./mysql.class.php");
include_once("./redis.class.php");
include_once("./logger.php");
include_once("./connConfig.php");



function recv_post_data() {
	$PostData = file_get_contents("php://input") ? file_get_contents("php://input") : gzuncompress($GLOBALS['HTTP_RAW_POST_DATA']);
	return $PostData;

}

function record_post_data($PostData) {
	
    $date_dir = dirname(__FILE__).'/datalog/'.date('Y-m-d',time());
	if ( !is_dir( $date_dir ) ) {
        mkdir($date_dir, 0700);
    }
    file_put_contents($date_dir. '/' .rand(1000,9999). '-' .time(). '.txt', $PostData);
}

function parse_post_data($PostData) {
	global $platpkey;
	if(!parseResp($PostData, $platpkey, $respJson)) {
		Config::$lg->info("parse resp data failed!");
		echo "parse resp data failed!\n";
	}
	return $respJson;
}

function connect_db(&$redis, &$mysql, $uid) {
    $ret = $mysql->connect(Config::$mysql_config);
    if (!$ret) {
        echo("mysql connect error.\n");
		Config::$lg->info("mysql connect error.");
        exit(0);
    }

    $ret = $redis->initCacheRedis();
    if (!$ret) {
        echo("cache redis connect error.\n");
		Config::$lg->info("cache redis connect error.");
        exit(0);
    }

    $ret = $redis->initDataRedis($uid);
    if(!$ret) {
        echo("data redis connect error.\n");
		Config::$lg->info("data redis connect error.");
        exit(0);
    }
}

function process($respJson,&$payInfArr, &$redis, &$mysql) {
    //错误返回
    if ( isset($respJson->code) ) {
       // echo $respJson->code;
        //echo $respJson->errmsg;
        echo "FAILURE";
		Config::$lg->info("FAILURE");
        exit(0);
    }
  
    //正确返回
    $cporderid = (string)$respJson->cporderid;
    $transid = (string)$respJson->transid;
    $uid = (int)$respJson->appuserid;
    $appid = (string)$respJson->appid;
    $gid = (int)$respJson->waresid;
    $feetype = (int)$respJson->feetype;
    $rmb = (float)$respJson->money;
    $result = (int)$respJson->result;
    $transtime = (string)$respJson->transtime;

    if ($result != 0){
        //echo $result;
        echo "FAILURE";
		Config::$lg->info("FAILURE2");
        exit(0);
    }

    $row = $mysql->select('applypay','*',array('orderid' => $cporderid));
    if ( count($row) == 0) {
		
        echo "FAILURE";
		Config::$lg->info("FAILURE3");
        exit(0);
    }

    $payInfArr = $row[0];
    $uid = (int)$payInfArr['uid'];
    $is_send = (int)$payInfArr['is_send'];


    if ($is_send == 1) {
        echo "repead order.";
        echo "FAILURE";
		Config::$lg->info("repead order.");
        exit(0);
    }

    $mysql->update('applypay',array('is_send' => 1),array('orderid' => $cporderid) );

    //处理充值，加金币或道具
    $goodsadd = $redis->cache_redis->hMGet("hg:{$gid}", array("money", "give_money"));
    $add_money = (int)$goodsadd['money'] + ((int)$goodsadd['money']*((int)$goodsadd['give_money']/100));
    $cur_coin = $redis->data_redis->hincrBY("hu:{$uid}", "coin", $add_money);
    //$cur_changeCardtool = $redis->data_redis->hincrBY("hu:{$uid}", "changeCardtoolNum", $goodsadd['changeCardtool']);
    //$cur_betsDoubletool = $redis->data_redis->hincrBY("hu:{$uid}", "betsDoubletoolNum", $goodsadd['betsDoubletool']);
    //$cur_banComparetool = $redis->data_redis->hincrBY("hu:{$uid}", "banComparetoolNum", $goodsadd['banComparetool']);
}

function insert_pay_record(&$mysql, $payInfArr) {
    //插入充值记录
    $payrecord = array();
    $payrecord['uid'] = (int)$payInfArr['uid'];
    $payrecord['rmb'] = (float)$payInfArr['price'];
    $payrecord['vercode'] = $payInfArr['version'];
    $payrecord['ua'] = $payInfArr['ua'];
    $payrecord['imsi'] = $payInfArr['imsi'];
    $payrecord['imei'] = $payInfArr['imei'];
    $payrecord['cid'] = $payInfArr['cid'];
    $payrecord['type'] = 1;
    $payrecord['create_time'] = time();
    $mysql->insert('payrecord', $payrecord);
}

function sys_task_of_pay($uid,&$redis) {
    //首次冲值奖券任务是否完成
    //从奖券任务记录字段中获取奖券任务完成度
    $task_id = 2;//任务号为2
    $task_complete_record_str = $redis->data_redis->hget("hu:{$uid}", "coin_task_complete_record");
    $task_pieces = explode("|", $task_complete_record_str);
    $task_value = $redis->cache_redis->hget("hcointask:{$task_id}", "task_value");
    //如果任务完成度 < 最大任务完成值,则任务完成度加1
    if ((int)$task_pieces[$task_id - 1] < (int)$task_value) {
        $task_pieces[$task_id - 1] += 1;
        //重新组装，任务奖励记录字符串
        $size = count($task_pieces);
        $str = "";
        for ($i = 0; $i < $size; $i++) {
            $str .= $task_pieces[$i];
            if ($i < $size - 1) {
                $str .= "|";
            }
        }
        //重新设置任务奖励记录字符串
        $redis->data_redis->hset("hu:{$uid}", "coin_task_complete_record", $str);
    }
}

function do_trade() {
	$PostData = recv_post_data();
    record_post_data($PostData);
    $PostData = urldecode($PostData);
	$respJson= parse_post_data($PostData);
    $redis = new RedisDriver();
	
    $mysql = new MysqlDriver();
    $uid = (int)$respJson->appuserid;
    connect_db($redis, $mysql,$uid);
    process($respJson,$payInfArr,$redis, $mysql);
    insert_pay_record($mysql,$payInfArr);
    //sys_task_of_pay($uid,$redis);
    $redis->deinitDataRedis();
    $redis->deinitCacheRedis();
    $mysql->close();
	$userinfo = $redis->data_redis->hget("hu:{$uid}",array("coin"));
	$coin = $userinfo['coin'];
	$uid = '9266';
    $purshurl = 'http://'.Config::$ip_server_confing['ip'].':'.Config::$ip_server_confing['myport'].'/pushsrv?action=upcoin&param={coin:'.$coin.'}';
	$this->http->get($purshurl);
    Config::$lg->info("SUCCESS");
    echo "SUCCESS";
}

do_trade();

?>
